<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/6
 * Time: 10:17
 */

namespace app\qgroup\service;


use app\common\service\BaseService;
use app\common\service\SysConfigService;
use app\common\util\StringUtil;

class XiaoIService extends BaseService
{
    /**
     * @param $data string JSON格式数据
     * @param null|string $url 访问URL
     * @return mixed
     */
    public function sendMessage($data,$url = null){
        $url = $url?:SysConfigService::getURLConfig('A_XIAOI');
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->sign(SysConfigService::getSysConfig('xi.app.key'),SysConfigService::getSysConfig('xi.app.secret'),explode('/',$url)[count(explode('/',$url))-1],'POST'));
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 签名
     * @param $app_key string
     * @param $app_secret string
     * @param string $uri string
     * @param string $method
     * @return array
     */
    public function sign($app_key,$app_secret,$uri="/ask.do",$method = 'POST')
    {
        $realm = 'xiaoi.com';
        $nonce = StringUtil::getNonceString(40);
        $HA1 = sha1($app_key . ":" . $realm . ":" . $app_secret);
        $HA2 = sha1($method . ":" . $uri);
        $sign = sha1($HA1 . ":" . $nonce . ":" . $HA2);
        $x = 'app_key='.$app_key.',nonce='.$nonce.',signature='.$sign;
        var_dump($x);
        return ['X-Auth:'.$x,'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'];
    }
}